package com.yc.vcode.web;

import com.yc.vcode.bean.Result;
import com.yc.vcode.bean.VcodeProperties;
import com.yc.vcode.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("vcode")
public class VcodeDo {

    @Autowired
    VcodeProperties properties;

    //验证启动器
    @RequestMapping("props")
    VcodeProperties properties(){
        return properties;
    }

    //生成验证码图片                       返回值类型
    @RequestMapping(value = "image", produces = MediaType.IMAGE_JPEG_VALUE)
    public void image(HttpServletResponse response, HttpSession session) throws IOException {
        //工具类方法，传入一个响应对象，生成验证码图片
        String vcode = VerifyCodeUtils.outputImage(response);

        //生成的验证码存入会话
        session.setAttribute("vcode", vcode);
    }

    //发送邮件
    @RequestMapping("email")
    public Result email(String email, String title, HttpSession session){
        //过滤            从配置获取
        String content = properties.getMsgs()
                .stream()
                .filter(m->m.get("title").equals(title))
                .findFirst()
                .get()
                .get("content");
        //获取时间戳后4位
        String vcode = "" + System.currentTimeMillis();
        vcode = vcode.substring(vcode.length() - 4);
        //存入会话
        session.setAttribute("ecode", vcode);
        content += vcode;
        sendSimpleMail(email, title, content);
        return new Result(1, "验证码发送至邮箱:" + email, null);
    }

    //发送邮件
    @RequestMapping("pwdemail")
    public Result pwdemail(String email, String title, HttpSession session){
        //过滤            从配置获取
        String content = properties.getMsgs()
                .stream()
                .filter(m->m.get("title").equals(title))
                .findFirst()
                .get()
                .get("content");
        //获取时间戳后4位
        String vcode = "" + System.currentTimeMillis();
        vcode = vcode.substring(vcode.length() - 4);
        //存入会话
        session.setAttribute("pwdcode", vcode);
        content += vcode;
        sendSimpleMail(email, title, content);
        return new Result(1, "验证码发送至邮箱:" + email, null);
    }


    //邮件        邮件发送器
    @Autowired
    private JavaMailSender mailSender;

    public void sendSimpleMail(String to, String subject, String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(properties().getFrom());
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
}
